// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const JOB_COLLECTION = 'job'
const DELIVER_RECORD_COLLECTION = 'deliver_record' // 投递记录
const USER_COLLECTION = 'user'
const COLLECTION_RECORD_COLLECTION = 'collection_record' // 收藏记录

// 获取数据库引用
const db = cloud.database()

/**
 * 云函数入口函数
 * @param {Object} event - 请求参数
 * @param {string} event.action - 操作类型
 * @param {Object} event.data - 操作数据
 * @returns {Object} 响应结果
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event
  switch (action) {
    case 'getJobList':
      return await getJobList(data)
    case 'getJobDetail':
      return await getJobDetail(event.jobId)
    case 'getSimilarJobs':
      return await getSimilarJobs()
    case 'getUserResume':
      return await getUserResume(wxContext.OPENID)
    case 'updateUserResume':
      return await updateUserResume(wxContext.OPENID, event.resumeUrl)
    case 'getDeliveryRecords':
      return await getDeliveryRecords(wxContext.OPENID)
    case 'createDeliveryRecord':
      return await createDeliveryRecord(wxContext.OPENID, data)
    case 'getCollectionRecords':
      return await getCollectionRecords(wxContext.OPENID)
    case 'toggleCollection':
      return await toggleCollection(wxContext.OPENID, data)
    case 'checkCollectionStatus':
      return await checkCollectionStatus(wxContext.OPENID, event.jobId)
    default:
      return {
        success: false,
        message: `未知的操作类型: ${action}`
      }
  }
}

/**
 * 获取职位列表
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {Array} returns.data - 职位列表
 * @returns {Object} returns.data[]._id - 职位ID
 * @returns {string} returns.data[].jobName - 职位名称
 * @returns {string} returns.data[].address - 工作地点
 * @returns {string} returns.data[].salary - 薪资范围
 * @returns {string} returns.data[].time - 发布时间
 * @returns {string} returns.data[].exp - 工作经验要求
 * @returns {string} returns.data[].degree - 学历要求
 * @returns {string} returns.data[].shortdec - 职位描述
 * @returns {string} returns.data[].detailAddress - 详细地址
 * @returns {string} returns.data[].companyName - 公司名称
 */
const getJobList = async () => {
  try {
    const jobs = await db.collection(JOB_COLLECTION)
      .orderBy('createTime', 'desc')
      .get()
    
    // 格式化数据以匹配前端需要的格式
    const formattedJobs = jobs.data.map(job => ({
      id: job._id,
      jobName: job.jobName,
      address: job.address,
      salary: job.salary,
      time: job.time || '1天前发布',
      exp: job.exp,
      degree: job.degree,
      shortdec: job.shortdec,
      detailAddress: job.detailAddress,
      companyName: job.companyName || '有赞',
      similarJob: job.similarJob || {
        id: '',
        jobName: '',
        address: '',
        exp: '',
        degree: '',
        salary: '',
        time: ''
      }
    }))
    
    return {
      success: true,
      data: formattedJobs
    }
  } catch (error) {
    console.error('获取职位列表失败:', error)
    return {
      success: false,
      message: '获取职位列表失败'
    }
  }
}

/**
 * 获取职位详情
 * @param {string} jobId - 职位ID
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {Object} returns.data - 职位详情
 * @returns {string} returns.data._id - 职位ID
 * @returns {string} returns.data.jobName - 职位名称
 * @returns {string} returns.data.address - 工作地点
 * @returns {string} returns.data.salary - 薪资范围
 * @returns {string} returns.data.time - 发布时间
 * @returns {string} returns.data.exp - 工作经验要求
 * @returns {string} returns.data.degree - 学历要求
 * @returns {string} returns.data.shortdec - 职位描述
 * @returns {string} returns.data.detailAddress - 详细地址
 * @returns {string} returns.data.companyName - 公司名称
 */
async function getJobDetail(id) {
  console.log("-------id---------", id)
  try {
    const job = await db.collection(JOB_COLLECTION).doc(id).get();
    if (!job.data) {
      throw new Error('职位不存在')
    }

    return {
      success: true,
      data: job.data
    }
  } catch (error) {
    console.error('获取职位详情失败:', error)
    return {
      success: false,
      message: '获取职位详情失败'
    }
  }
}

/**
 * 获取相似职位
 * @param {string} jobId - 当前职位ID
 * @param {string} jobName - 当前职位名称
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {Array} returns.data - 相似职位列表
 * @returns {Object} returns.data[]._id - 职位ID
 * @returns {string} returns.data[].jobName - 职位名称
 * @returns {string} returns.data[].address - 工作地点
 * @returns {string} returns.data[].salary - 薪资范围
 * @returns {string} returns.data[].time - 发布时间
 * @returns {string} returns.data[].exp - 工作经验要求
 * @returns {string} returns.data[].degree - 学历要求
 * @returns {string} returns.data[].shortdec - 职位描述
 * @returns {string} returns.data[].detailAddress - 详细地址
 * @returns {string} returns.data[].companyName - 公司名称
 */
async function getSimilarJobs() {
  return {
    success: true,
    data: similarJobs.data
  }
}

/**
 * 获取用户简历信息
 * @param {string} openid - 用户openid
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {string} returns.resumeUrl - 简历文件地址
 */
async function getUserResume(openid) {
  try {
    const userInfo = await db.collection(USER_COLLECTION)
      .where({ _openid: openid })
      .get()
    
    if (userInfo.data.length > 0) {
      return {
        success: true,
        resumeUrl: userInfo.data[0].resumeUrl || ''
      }
    }
    return {
      success: true,
      resumeUrl: ''
    }
  } catch (error) {
    console.error('获取用户简历失败:', error)
    return {
      success: false,
      message: '获取用户简历失败'
    }
  }
}

/**
 * 更新用户简历信息
 * @param {string} openid - 用户openid
 * @param {string} resumeUrl - 简历文件地址
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 */
async function updateUserResume(openid, resumeUrl) {
  try {
    const userInfo = await db.collection(USER_COLLECTION)
      .where({ _openid: openid })
      .get()
    
    if (userInfo.data.length > 0) {
      // 更新现有用户
      await db.collection(USER_COLLECTION)
        .where({ _openid: openid })
        .update({
          data: {
            resumeUrl: resumeUrl,
            updateTime: db.serverDate()
          }
        })
    } else {
      // 创建新用户
      await db.collection(USER_COLLECTION).add({
        data: {
          _openid: openid,
          resumeUrl: resumeUrl,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
    }
    
    return {
      success: true
    }
  } catch (error) {
    console.error('更新用户简历失败:', error)
    return {
      success: false,
      message: '更新用户简历失败'
    }
  }
}

/**
 * 获取投递记录
 * @param {string} openid - 用户openid
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {Array} returns.records - 投递记录列表
 * @returns {Object} returns.records[]._id - 记录ID
 * @returns {string} returns.records[].jobId - 职位ID
 * @returns {string} returns.records[].jobName - 职位名称
 * @returns {string} returns.records[].companyName - 公司名称
 * @returns {string} returns.records[].salary - 薪资范围
 * @returns {string} returns.records[].location - 工作地点
 * @returns {string} returns.records[].status - 投递状态
 * @returns {Date} returns.records[].createTime - 投递时间
 */
async function getDeliveryRecords(openid) {
  try {
    const records = await db.collection(DELIVER_RECORD_COLLECTION)
      .where({ _openid: openid })
      .orderBy('createTime', 'desc')
      .get()
    
    return {
      success: true,
      records: records.data
    }
  } catch (error) {
    console.error('获取投递记录失败:', error)
    return {
      success: false,
      message: '获取投递记录失败'
    }
  }
}

/**
 * 创建投递记录
 * @param {string} openid - 用户openid
 * @param {Object} data - 投递数据
 * @param {string} data.jobId - 职位ID
 * @param {string} data.jobName - 职位名称
 * @param {string} data.companyName - 公司名称
 * @param {string} data.salary - 薪资范围
 * @param {string} data.location - 工作地点
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 */
async function createDeliveryRecord(openid, data) {
  try {
    await db.collection(DELIVER_RECORD_COLLECTION).add({
      data: {
        _openid: openid,
        jobId: data.jobId,
        jobName: data.jobName,
        companyName: data.companyName,
        salary: data.salary,
        location: data.location,
        status: 'pending',
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    })
    
    return {
      success: true
    }
  } catch (error) {
    console.error('创建投递记录失败:', error)
    return {
      success: false,
      message: '创建投递记录失败'
    }
  }
}

/**
 * 获取收藏记录
 * @param {string} openid - 用户openid
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {Array} returns.records - 收藏记录列表
 */
async function getCollectionRecords(openid) {
  try {
    const records = await db.collection(COLLECTION_RECORD_COLLECTION)
      .where({ _openid: openid })
      .orderBy('createTime', 'desc')
      .get()
    
    // 格式化数据以匹配前端需要的格式
    const formattedRecords = records.data.map(record => ({
      id: record.jobId,
      jobName: record.jobName,
      address: record.location,
      salary: record.salary,
      time: '已收藏',
      exp: '',
      degree: '',
      shortdec: '',
      detailAddress: '',
      companyName: record.companyName,
      similarJob: {
        id: '',
        jobName: '',
        address: '',
        exp: '',
        degree: '',
        salary: '',
        time: ''
      }
    }))
    
    return {
      success: true,
      records: formattedRecords
    }
  } catch (error) {
    console.error('获取收藏记录失败:', error)
    return {
      success: false,
      message: '获取收藏记录失败'
    }
  }
}

/**
 * 切换收藏状态
 * @param {string} openid - 用户openid
 * @param {Object} data - 收藏数据
 * @param {string} data.jobId - 职位ID
 * @param {string} data.jobName - 职位名称
 * @param {string} data.companyName - 公司名称
 * @param {string} data.salary - 薪资范围
 * @param {string} data.location - 工作地点
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {boolean} returns.isCollected - 当前收藏状态
 */
async function toggleCollection(openid, data) {
  try {
    // 检查是否已收藏
    const existingRecord = await db.collection(COLLECTION_RECORD_COLLECTION)
      .where({
        _openid: openid,
        jobId: data.jobId
      })
      .get()

    if (existingRecord.data.length > 0) {
      // 取消收藏
      await db.collection(COLLECTION_RECORD_COLLECTION)
        .where({
          _openid: openid,
          jobId: data.jobId
        })
        .remove()
      
      return {
        success: true,
        isCollected: false
      }
    } else {
      // 添加收藏
      await db.collection(COLLECTION_RECORD_COLLECTION).add({
        data: {
          _openid: openid,
          jobId: data.jobId,
          jobName: data.jobName,
          companyName: data.companyName,
          salary: data.salary,
          location: data.location,
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
      
      return {
        success: true,
        isCollected: true
      }
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    return {
      success: false,
      message: '切换收藏状态失败'
    }
  }
}

/**
 * 检查收藏状态
 * @param {string} openid - 用户openid
 * @param {string} jobId - 职位ID
 * @returns {Object} 响应结果
 * @returns {boolean} returns.success - 是否成功
 * @returns {boolean} returns.isCollected - 是否已收藏
 */
async function checkCollectionStatus(openid, jobId) {
  try {
    const record = await db.collection(COLLECTION_RECORD_COLLECTION)
      .where({
        _openid: openid,
        jobId: jobId
      })
      .get()
    
    return {
      success: true,
      isCollected: record.data.length > 0
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return {
      success: false,
      message: '检查收藏状态失败'
    }
  }
}

